package com.usian.listener;

import com.rabbitmq.client.Channel;
import com.usian.JsonUtils;
import com.usian.mapper.DeDuplicationMapper;
import com.usian.pojo.DeDuplication;
import com.usian.pojo.DeDuplicationExample;
import com.usian.pojo.LocalMessage;
import com.usian.service.ItemService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ItemMQListener {

    @Autowired
    private ItemService itemService;

    @Autowired
    private DeDuplicationMapper deDuplicationMapper;

    /**
     * 监听者接收消息三要素：
     *  1、queue
     *  2、exchange
     *  3、routing key
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value="item_queue",durable = "true"),
            exchange = @Exchange(value="order_exchange",type= ExchangeTypes.TOPIC),
            key= {"*.*"}
    ))
    public void listen(String msg, Channel channel, Message message) throws Exception {
        LocalMessage localMessage = JsonUtils.jsonToPojo(msg, LocalMessage.class);
//        幂等校验
        DeDuplication deDuplication = deDuplicationMapper.selectByPrimaryKey(localMessage.getTxNo());

            if (deDuplication==null){
//                执行扣减库存
                Integer result = itemService.updateTbItemByOrderId(localMessage.getOrderNo());
                if (!(result>0)){
                    throw new RuntimeException("扣减失败");
                }
//                记录成功执行过得事务
                DeDuplication deDuplication1 = new DeDuplication();
                deDuplication1.setTxNo(localMessage.getTxNo());
                deDuplication1.setCreateTime(new Date());
                deDuplicationMapper.insertSelective(deDuplication1);
            }

//        执行手动ack消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        System.out.println("接收到消息：" + orderId);
//        Integer result = itemService.updateTbItemByOrderId(orderId);
//        if(!(result>0)){
//            throw new RuntimeException("扣减失败");
//        }
    }
}
